package rad.framework.mda.jpagen.actions;

import rad.framework.mda.generator.Console;
import rad.framework.mda.util.ModelUtil;

import org.eclipse.emf.common.util.EList;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.uml2.uml.Association;
import org.eclipse.uml2.uml.Class;
import org.eclipse.uml2.uml.NamedElement;
import org.eclipse.uml2.uml.Property;
import org.eclipse.uml2.uml.Stereotype;

/**
 * @author boudyacho
 * 
 */
public class IndexManyToOneActionExtension extends BaseUtiltiyActionExtension {

	protected static final String INDEX = "org.hibernate.annotations.Index";

	public void fillContextMenu(IMenuManager aMenu) {
		getSubMenu(aMenu).add(new IndexManyToOneAction());
	}

	protected void execute(Class clazz) {
		EList<NamedElement> list = clazz.getMembers();
		for (NamedElement namedElement : list) {
			if (namedElement instanceof Property) {
				execute((Property) namedElement);
			}
		}
	}

	protected void execute(Property property) {
		if (ModelUtil.isStereotypeApplied(property, M2O)) {
			setIndex(property);
		}
	}

	protected void setIndex(Property element) {
		Stereotype stereotype = (Stereotype) ModelUtil.getProfileElement(
				element, INDEX);
		if (stereotype != null) {
			if (!ModelUtil.isStereotypeApplied(element, INDEX)) {
				element.applyStereotype(stereotype);
				Console.getStream().println(
						"Added " + INDEX + " stereotype - "
								+ element.getQualifiedName());
			}
			Class clazz = (Class) element.getOwner();
			String tableName = NameUtil.getAbbreviation(clazz);
			String propertyName = NameUtil.getAbbreviation(element);
			String indexName = tableName + "_" + propertyName + "_IDX";
			indexName = NameUtil.getAbbreviation(indexName);
			checkLength(element, indexName, 30);
			element.setValue(stereotype, "name", indexName);
		}
	}

	private class IndexManyToOneAction extends BaseUtilityAction {
		private static final String LABEL = "Add Index Stereotype to ManyToOne Properties";

		public IndexManyToOneAction() {
			super(LABEL);
		}
	}
}
